package com.sugon.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.SysUserDao;
import com.sugon.entity.SysUserEntity;
import com.sugon.service.SysUserRoleService;
import com.sugon.service.SysUserService;
import com.sugon.utils.Constant;
import com.sugon.utils.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 系统用户
 *
 * @author 李鹏军
 * @date 2016年12月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * fasfasfasfasf
     *
     * @param workshopId
     * @return
     */
    @Override
    public List<SysUserEntity> listSpareApprover(String workshopId) {
        List<SysUserEntity> workshopLeaders = sysUserDao.queryWorkshopLeader(workshopId);
        return Optional.ofNullable(workshopLeaders).orElseGet(() -> CollectionUtil.newArrayList());
    }

    /**
     * fasfasfasfasf
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> queryAllMenuId(String userId) {
        return sysUserDao.queryAllMenuId(userId);
    }

    /**
     * fasfasfasfasf
     *
     * @param username
     * @return
     */
    @Override
    public SysUserEntity queryByUserName(String username) {
        return sysUserDao.queryByUserName(username);
    }

    /**
     * fasfasfasfasf
     *
     * @param nickname
     * @return
     */
    @Override
    public SysUserEntity queryByNickname(String nickname) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("nickName", nickname);
        List<SysUserEntity> users = queryList(param);
        return CollectionUtil.isNotEmpty(users) ? users.get(0) : null;
    }

    /**
     * fasfasfasfasf
     *
     * @param userId
     * @return
     */
    @Override
    public SysUserEntity queryObject(String userId) {
        return sysUserDao.queryObject(userId);
    }

    /**
     * fasfasfasfasf
     *
     * @param unionId
     * @return
     */
    @Override
    public SysUserEntity queryByUnionId(String unionId) {
        Map<String, Object> param = new HashMap<>();
        param.put("unionId", unionId);
        List<SysUserEntity> sysUserEntities = sysUserDao.queryList(param);
        return CollectionUtil.isEmpty(sysUserEntities) ? null : sysUserEntities.get(0);
    }

    /**
     * fasfasfasfasf
     *
     * @param map
     * @return
     */
    @Override
//    @DataFilter(userAlias = "r.create_user", deptAlias = "r.dept_id")
    public List<SysUserEntity> queryList(Map<String, Object> map) {
        return sysUserDao.queryList(map);
    }

    /**
     * fasfasfasfasf
     *
     * @param map
     * @return
     */
    @Override
//    @DataFilter(userAlias = "r.create_user", deptAlias = "r.dept_id")
    public int queryTotal(Map<String, Object> map) {
        return sysUserDao.queryTotal(map);
    }

    /**
     * fasfasfasfasf
     *
     * @param user
     */
    @Override
    @Transactional
    public void save(SysUserEntity user) {
        String userId = RandomUtil.randomString(32);
        user.setUserId(userId);
        user.setCreateTime(new Date());
        user.setDelFlag(Constant.IS_NOT_DEL_INT);
        user.setCreateUser(ShiroUtils.getUserId());
        //base64加密
        user.setPassWord(Base64.encode(Constant.DEFAULT_PASS_WORD));
        String deptCode = user.getDeptId();
        if (deptCode.length() > 4) {
            user.setDeptCode(deptCode.substring(0, 4));
        } else {
            user.setDeptCode(deptCode);
        }
        sysUserDao.save(user);
        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(userId, user.getRoleIdList());
    }

    /**
     * fasfasfasfasf
     *
     * @param user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassWord())) {
            user.setPassWord(new Sha256Hash(Constant.DEFAULT_PASS_WORD).toHex());
        } else {
            user.setPassWord(new Sha256Hash(user.getPassWord()).toHex());
        }
        user.setUpdateTime(DateUtil.date());
        user.setUpdateUser(ShiroUtils.getUserId());
        // 设置部门编码
        String deptId = user.getDeptId();
        if (StrUtil.isNotEmpty(deptId)) {
            if (deptId.length() >= 4) {
                user.setDeptCode(deptId.substring(0, 4));
            } else {
                user.setDeptCode(deptId);
            }
        }
        sysUserDao.update(user);
        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    /**
     * fasfasfasfasf
     *
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] userId) {
        // 1、批量删除用户-角色关联
        if (ArrayUtil.isNotEmpty(userId)) {
            for (int i = 0; i < userId.length; i++) {
                sysUserRoleService.delete(userId[i]);
            }
        }
        // 2、批量删除用户
        sysUserDao.deleteBatch(userId);
    }

    /**
     * fasfasfasfasf
     *
     * @param userId      用户ID
     * @param password    原密码
     * @param newPassword 新密码
     * @return
     */
    @Override
    public int updatePassword(String userId, String password, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("password", password);
        map.put("newPassword", newPassword);
        return sysUserDao.updatePassword(map);
    }

    /**
     * fasfasfasfasf
     *
     * @return
     */
    @Override
    public SysUserEntity getPE() {
        return sysUserDao.getPE();
    }

    /**
     * fasfasfasfasf
     *
     * @param map
     * @return
     */
    @Override
    public List<SysUserEntity> treeDeptByParent(Map<String, Object> map) {
        return sysUserDao.treeDeptByParent(map);
    }

    /**
     * fasfasfasfasf
     *
     * @param roleCode
     * @return
     */
    @Override
    public List<SysUserEntity> queryAllRoleUser(String roleCode) {
        List<SysUserEntity> users = sysUserDao.queryAllRoleUser(roleCode);
        return users == null ? new ArrayList<>() : users;
    }

    /**
     * 目前特权用户认定：具有超级管理员、基础数据维护员、管理员 三个角色的
     */
    @Override
    public boolean isPrivilegeUser(String userId) {
        List<String> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            for (String roleId : roleIdList) {
                if (StrUtil.equalsAny(roleId, Constant.SUPER_ADMIN_ROLE, Constant.BASE_DATA_MANAGER_ROLE, Constant.SYSTEM_ADMIN_ROLE)) {
                    return true;
                }
            }
        }
        return false;
    }
}
